﻿namespace GreenIsomer.Web.Controls.JQuery {
	using System;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.ComponentModel;

	/// <summary>
	/// Server control used to generate inner markup needed for each panel of a jQuery UI Accordion widget.
	/// </summary>
	[ParseChildren(false), PersistChildren(true)]
	public class AccordionPanel : WebControl {


		#region Constants: Property defaults

		private const string defaultHeaderText = "";

		#endregion


		#region Constructors

		/// <summary>
		/// Initializes a new instance of the GreenIsomer.Web.Controls.JQuery.AccordionPanel class.
		/// </summary>
		public AccordionPanel() : base(HtmlTextWriterTag.Div) { }

		#endregion


		#region Properties

		/// <summary>
		/// The text that will be rendered into the jQuery UI Accordion widget section's header.
		/// </summary>
		[DefaultValue(defaultHeaderText), Category("Appearance")]
		public virtual string HeaderText {
			get { return ViewState.GetValue("HeaderText", defaultHeaderText); }
			set { ViewState["HeaderText"] = value; }
		}

		#endregion


		#region Methods: Rendering hooks

		/// <summary>
		/// Outputs the content of a server control's children to a provided System.Web.UI.HtmlTextWriter object, which writes the content to be rendered on the client.
		/// This method is used primarily by control developers.
		/// </summary>
		/// <param name="writer">The System.Web.UI.HtmlTextWriter object that receives the rendered content.</param>
		protected override void RenderChildren(HtmlTextWriter writer) {
			HeaderLevel? header = GetHeader();
			string headingText = HeaderText;

			bool renderHeadingAndDiv = header.HasValue || !string.IsNullOrEmpty(headingText);
			bool renderAnchor = header.HasValue;

			string headingTagName = header.HasValue ? ScriptBuilder.GetCamelCaseEnumValue(header.Value) : "div";

			if(renderHeadingAndDiv) {
				writer.RenderBeginTag(headingTagName);                 //<h?>

				if(renderAnchor) {                                     //<a>
					writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
					writer.RenderBeginTag(HtmlTextWriterTag.A);
				}
				writer.WriteEncodedText(headingText);
				if(renderAnchor) writer.RenderEndTag();                //</a>

				writer.RenderEndTag();                                 //</h?>

				writer.RenderBeginTag(HtmlTextWriterTag.Div);          //<div>
			}

			base.RenderChildren(writer);

			if(renderHeadingAndDiv) writer.RenderEndTag();             //</div>
		}

		#endregion


		#region Routines

		private HeaderLevel? GetHeader() {
			Accordion accordion = Parent as Accordion;
			if(accordion == null) return null;
			return accordion.Header;
		}

		#endregion


	}

}